package jehc.djshi.job.command;

import jehc.djshi.common.cache.redis.RedisUtil;
import jehc.djshi.common.util.RestTemplateUtil;
import jehc.djshi.job.model.JobConfig;
import jehc.djshi.job.service.JobConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import java.text.SimpleDateFormat;
import java.util.*;
import org.quartz.Scheduler;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
/**
 * 调度认为
 * @author 邓纯杰
 *
 */
@Slf4j
@Component
@Order(0)
public class InitScheduler implements CommandLineRunner {

    @Resource
    RestTemplateUtil restTemplateUtil;

    @Resource
    RedisUtil redisUtil;

    @Resource
    JobConfigService jobConfigService;

    @Resource
    Scheduler schedulerFactoryBean;

    /**
     * 加载调度器设置
     */
    private void init() {
        Timer timer = new Timer("InitScheduler", true);
        timer.schedule(new TimerTask() {
            public void run() {
                List<JobConfig> jobConfigs = jobConfigService.getJobConfigListByCondition(new HashMap<>());
        		for(int i = 0; i < jobConfigs.size(); i++){
                    JobConfig jobConfig = jobConfigs.get(i);
        			new JobInit(schedulerFactoryBean, jobConfig.getId(), jobConfig.getJobName(), jobConfig.getJobGroup(), jobConfig.getCronExpression(), jobConfig.getDesc_(), jobConfig.getClientId(), jobConfig.getClientGroupId(),jobConfig.getJobHandler(),jobConfig.getJobPara(),jobConfig.getJobTitle()).start();//需要重新修改
        		}
            }
        }, 1 * 10);
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            log.info(sdf.format(new Date())+"--->初始化调度任务............");
            init();
            log.info(sdf.format(new Date())+"--->调度任务完毕............");
        } catch (Exception e) {

        }
    }
}
